package com.plugins.utils;

import android.os.AsyncTask;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileDownloader {

    public interface DownloadCallback {
        void onProgressUpdate(int progress);
        void onDownloadComplete();
        void onDownloadFailed(String errorMessage);
    }

    public void downloadFile(String fileUrl, String destinationPath, DownloadCallback callback) {
        new DownloadFileTask(callback).execute(fileUrl, destinationPath);
    }

    private class DownloadFileTask extends AsyncTask<String, Integer, Boolean> {
        private DownloadCallback callback;

        public DownloadFileTask(DownloadCallback callback) {
            this.callback = callback;
        }

        @Override
        protected Boolean doInBackground(String... params) {
            String fileUrl = params[0];
            String destinationPath = params[1];
            try {
                URL url = new URL(fileUrl);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.connect();

                int fileLength = urlConnection.getContentLength();

                InputStream input = new BufferedInputStream(url.openStream());
                FileOutputStream output = new FileOutputStream(destinationPath);

                byte data[] = new byte[1024];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {
                    total += count;
                    if (fileLength > 0) {
                        publishProgress((int) (total * 100 / fileLength));
                    }
                    output.write(data, 0, count);
                }

                output.flush();
                output.close();
                input.close();
                return true;
            } catch (Exception e) {
                Log.e("FileDownloader", "Error downloading file: " + e.getMessage());
                return false;
            }
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            callback.onProgressUpdate(values[0]);
        }

        @Override
        protected void onPostExecute(Boolean result) {
            if (result) {
                callback.onDownloadComplete();
            } else {
                callback.onDownloadFailed("Download failed");
            }
        }
    }
}
